/**
 * Copyright (c) 2012 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.view;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import chabernac.android.tools.SingleObjectQueue;
import chabernac.android.wordbattle.paint.iDrawable;

public class AnimationView extends View {
  public static final long DELAY = 1000 / 30;
  private SingleObjectQueue<iDrawable> myQueue = new SingleObjectQueue<iDrawable>();
  private ScheduledExecutorService myExecutorService = Executors.newScheduledThreadPool( 1 );
  private iDrawable myCurrentDrawable = null;
  private ScheduledFuture myScheduledTask = null;

  public AnimationView( Context aContext, AttributeSet aAttrs, int aDefStyle ) {
    super( aContext, aAttrs, aDefStyle );
  }

  public AnimationView( Context aContext, AttributeSet aAttrs ) {
    super( aContext, aAttrs );
  }

  public AnimationView( Context aContext ) {
    super( aContext );
  }

  public void start(){
    if(myScheduledTask == null || myScheduledTask.isCancelled()){
      myScheduledTask = myExecutorService.scheduleAtFixedRate( new Runnable(){
        public void run(){
          iDrawable theDrawable = myQueue.get();
          if(theDrawable != null){
            myCurrentDrawable = theDrawable;
            postInvalidate();
          }
        }
      }, DELAY, DELAY, TimeUnit.MILLISECONDS);
    }
  }

  public void stop(){
    myScheduledTask.cancel( false );
  }

  public void onDraw(Canvas aCanvas){
    if(myCurrentDrawable != null){
      Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
      myCurrentDrawable.paint( aCanvas, this );
    }
  }

  public SingleObjectQueue<iDrawable> getDrawableQueue(){
    return myQueue;
  }

}
